using Microsoft.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;
using Volo.Abp.EntityFrameworkCore.DependencyInjection;
using Joy.Erp.BasicArchives.EntityFrameworkCore;

namespace Joy.Erp.BasicArchives.ItemMasters
{
    public class UnitGroupModelConfiguration : IModelConfiguration
    {
        public void Build(ModelBuilder builder)
        {
            builder.Entity<UnitGroup>(b =>
            {
                b.ToTable(BasicArchivesDbProperties.DbTablePrefix + nameof(UnitGroup), BasicArchivesDbProperties.DbSchema);
                b.ConfigureByConvention();
                b.ConfigureMultiArchiveAggregateRoot<UnitGroup, AuxiliaryUnit>();

                b.Property(x => x.GroupName).HasMaxLength(UnitGroupConsts.GroupNameMaxLength);
                b.Property(x => x.GroupName).IsRequired(UnitGroupConsts.GroupNameRequired);
                b.Property(x => x.MainUnitId).IsRequired(UnitGroupConsts.MainUnitIdRequired);

                b.HasOne(x => x.MainUnit).WithMany().HasForeignKey(x => x.MainUnitId).OnDelete(DeleteBehavior.Restrict);
                b.HasMany(x => x.Children).WithOne(x => x.MainArchive).HasForeignKey(x => x.MainArchiveId).OnDelete(DeleteBehavior.Cascade);
            });
        }

        public void Entity(IAbpDbContextRegistrationOptionsBuilder options)
        {
            options.Entity<UnitGroup>(opt =>
            {
                opt.DefaultWithDetailsFunc = query =>
                {
                    return query
                        .Include(x => x.MainUnit)
                        .Include(x => x.Children)
                        ;
                };
            });
        }
    }
}
